<?php

namespace app\admin\controller;

use app\common\controller\Backend;

class Dashboard extends Backend
{
    public function initialize(): void
    {
        parent::initialize();
        $this->market_model = new \app\admin\model\Market();
        $this->device_model = new \app\admin\model\Device();
        $this->merchant_model = new \app\admin\model\Merchant();
        $this->complaint_model = new \app\admin\model\Complaint();
        $this->notice_model = new \app\admin\model\Notice();
    }

    public function index(): void
    {   
        $where = [];

        $startTime = strtotime('today');
        $endTime = strtotime('tomorrow') - 1;

        $auth = $this->auth->getInfo();
        $count['marketTotal'] = $this->market_model->where($where)->count();
        $count['deviceTotal'] = $this->device_model->where($where)->count();
        $count['merchantTotal'] = $this->merchant_model->where($where)->count();
        $count['complaintTotal'] = $this->complaint_model->where($where)->count();

        $count['processingDone'] = $this->complaint_model->where($where)->where("status",0)->count(); //待处理总数
        $count['completeComplaint'] = $this->complaint_model->where($where)->where("status",1)->count(); //已处理总数
        $count['todayComplaint'] = $this->complaint_model->where($where)->whereBetween("timestamp",[$startTime,$endTime])->count(); //今日投诉总数
        //$count['todayProcessing'] = $this->complaint_model->where($where)->whereBetween("timestamp",[$startTime,$endTime])->count(); //今日待处理

        //智慧党建id 
        $dj = 13;
        $w[] = ['type','<>',$dj];
        $news = $this->notice_model->with("parameter")->where($w)->select()->toArray();
        $news_dangjian = $this->notice_model->with("parameter")->where("type",$dj)->select()->toArray();

        //商户排行
        $merchant_complaint_rank = $this->complaint_model->alias('c')
                ->alias('c')
                ->join('market m', 'c.market_id = m.id')
                ->field('c.merchant_id, m.name as market_name, COUNT(*) as complaint_count')
                ->group('c.merchant_id, m.name') // 添加m.name到GROUP BY
                ->order('complaint_count', 'desc')
                ->limit(10)
                ->select()
                ->toArray();
        //市场排行
        $market_complaint_rank = $this->complaint_model->with("market")->field('market_id, COUNT(*) as complaint_count')
            ->group('market_id')
            ->order('complaint_count', 'desc')
            ->limit(10)
            ->select()
            ->toArray();
        $market_all = $this->market_model->field("name,lon,lat")->select();
        $this->success('', [
            'summary'=>$count,
            'news'=>$news,
            'news_dangjian'=>$news_dangjian,
            'merchant_complaint_rank'=>$merchant_complaint_rank,
            'market_complaint_rank'=>$market_complaint_rank,
            'market_all'=>$market_all,
            'remark' => get_route_remark()
        ]);
    }
}